﻿#region header

//  ***************************************************************************
// *                                LICENSE
//  ***************************************************************************
//  * "Haplous" .NET Simple 2D Game Framework
//  * 
//  * Copyright © Jonathan Evans 2014-2014
//  * 
//  * This program is free software; you can redistribute it and/or
//  * modify it under the terms of the GNU General Public License
//  * as published by the Free Software Foundation; either version 2
//  * of the License, or (at your option) any later version.
//  * 
//  * This program is distributed in the hope that it will be useful,
//  * but WITHOUT ANY WARRANTY; without even the implied warranty of
//  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  * GNU General Public License for more details.
//  * 
//  * You should have received a copy of the GNU General Public License
//  * along with this program; if not, write to the Free Software
//  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//  * 
//  ***************************************************************************
//  * 
//  * Contact: opencollar@googlemail.com
//  * 
//  * Website: http://haplous.codeplex.com/
//  *
//  * NuGet:   http://www.nuget.org/packages/haplous/
//  *
//  * File:    Haplous/Haplous/KeyboardDirector.cs
//  *
//  ***************************************************************************

#endregion

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Input;

using Haplous.Core;
using Haplous.Properties;

using JetBrains.Annotations;

namespace Haplous
{
    /// <summary>
    ///     A controller that allows key presses on the keyboard to control the movement of a Actor.
    /// </summary>
    [SuppressMessage("Microsoft.Maintainability", "CA1501:AvoidExcessiveInheritance")]
    [DebuggerDisplay("KeyboardDirector: Name={Name}")]
    public class KeyboardDirector : SynchronizedDirector
    {
        /// <summary>
        ///     The offset that will be applied to the current position (reused for efficiency).
        /// </summary>
        [NotNull]
        private readonly PositionInt32 _offset = new PositionInt32(0, 0);

        /// <summary>
        ///     The maximum size of any step.
        /// </summary>
        private readonly int _step;

        /// <summary>
        ///     A flag indicating whether or not this controller is enabled.
        /// </summary>
        private bool _enabled = true;

        /// <summary>
        ///     Initializes a new instance of the <see cref="ElementBase" /> class.
        /// </summary>
        /// <param name="game">
        ///     The game to which the class belongs.  The <paramref name="game" /> must not be
        ///     <see langword="null" />.
        /// </param>
        /// <param name="name">
        ///     The unique name that can be used to identify this object.  The <paramref name="name" /> must not be
        ///     <see langword="null" />, empty or all whitespace.
        /// </param>
        /// <param name="cue">The Cue that will be used to trigger movements.</param>
        /// <param name="stepSize">The size of each movement (in game pixels). Must be greater than zero.</param>
        /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="stepSize" /> must be greater than zero. </exception>
        /// <param name="actor">The Actor to control.  Must not be <see langword="null" />.</param>
        public KeyboardDirector([NotNull] Game game, [NotNull] string name, [NotNull] Actor actor, [NotNull] Cue cue, int stepSize) : base(game, name, actor, cue)
        {
            if(stepSize <= 0)
                throw new ArgumentOutOfRangeException("stepSize", stepSize, Resources.Error_StepSizeArgumentInvalid);
            _step = stepSize;
        }

        /// <summary>
        ///     A flag indicating whether or not this controller is enabled.
        /// </summary>
        public bool Enabled
        {
            get { return _enabled; }
            set { OnPropertyChanged("Enabled", ref _enabled, value); }
        }

        /// <summary>
        ///     Called when an update is required.
        /// </summary>
        protected override void OnTick()
        {
            if(!_enabled)
                return;

            _offset.Set(0, 0);
            Dispatcher.Invoke(() =>
                              {
                                  if(Keyboard.IsKeyDown(Key.Down))
                                      _offset.Y = _step;
                                  if(Keyboard.IsKeyDown(Key.Up))
                                      _offset.Y = _offset.Y - _step;

                                  if(Keyboard.IsKeyDown(Key.Left))
                                      _offset.X = -_step;
                                  if(Keyboard.IsKeyDown(Key.Right))
                                      _offset.X = _offset.X + _step;
                              });
            var previousX = Actor.Position.X;
            var previousY = Actor.Position.Y;

            ConfineToGameArea(_offset);
            Move(_offset);

            // Calculate the current direction
            var newX = Actor.Position.X;
            var newY = Actor.Position.Y;

            var newDirection = DirectionKind.None;
            if(newY > previousY)
                newDirection = DirectionKind.Down;
            else
            {
                if(newY < previousY)
                    newDirection = DirectionKind.Up;
            }
            if(newX > previousX)
                newDirection = DirectionKind.Right;
            else
            {
                if(newX < previousX)
                    newDirection = DirectionKind.Left;
            }
            CurrentDirection.Value = newDirection;
        }
    }
}